package com.framework.interceptor;

import cn.hutool.db.Session;
import com.framework.common.annotation.Login;
import com.framework.common.annotation.McnLogin;
import com.framework.common.exception.RRException;
import com.framework.common.utils.HttpContextUtils;
import com.framework.modules.base.entity.TokenEntity;
import com.framework.modules.base.entity.UserEntity;
import com.framework.modules.base.entity.UserInfoEntity;
import com.framework.modules.base.service.TokenService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * MCN管理客户端权限(Token)验证
 */
@Component
public class McnAuthorizationInterceptor extends HandlerInterceptorAdapter {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private TokenService tokenService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		McnLogin annotation;
		if (handler instanceof HandlerMethod) {
			annotation = ((HandlerMethod) handler).getMethodAnnotation(McnLogin.class);
		} else {
			return true;
		}

		if (annotation == null) {
			return true;
		}

		// 从header中获取token
		String token = request.getHeader("token");
		// 从header中获取token
		// 如果header中不存在token，则从参数中获取token
		if (StringUtils.isBlank(token)) {
			token = request.getParameter("token");
		}

		// token为空
		if (StringUtils.isBlank(token)) {
			throw new RRException("token不能为空");
		}

		// 查询token信息
		Map<String,Object> userMapData = tokenService.getUserinfo(token,"mcn");
		if (userMapData == null) {
			throw new RRException("您还没有登陆，请重新登陆", -101);
		}

		Long uid = Long.valueOf(userMapData.get("user_id").toString());
		Integer guildId = Integer.valueOf(userMapData.get("guild_id").toString());
		if(guildId <= 0) {
			throw new RRException("身份验证失败，您没有登陆权限", -102);
		}

		// 设置userId到request里，后续根据userId，获取用户信息
		request.setAttribute(HttpContextUtils.USER_KEY, uid);
		request.setAttribute(HttpContextUtils.MCN_GUILD_ID, guildId);
		return true;
	}
}
